package com.example.j2025_11_15.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.example.j2025_11_15.model.Session;
import com.example.j2025_11_15.model.Size;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;

@RestController
@RequestMapping("/captcha")
public class CaptchaController {

    @Autowired
    private Session Session;
    @Autowired
    private Size size;

    @RequestMapping("/getCaptcha")
    public void getCaptcha(HttpSession session , HttpServletResponse response){
        //定义图形验证码的长和宽
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(size.getWidth(), size.getLength());

        try {
            lineCaptcha.write(response.getOutputStream());
            session.setAttribute(Session.getKey(),lineCaptcha.getCode());
            session.setAttribute(Session.getDate(),new Date());
            //设置响应文本格式
            response.setContentType("image/jpeg");
            //禁⽌使⽤缓存
            response.setHeader("Pragma", "No-cache");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            System.out.println(lineCaptcha.getCode());
        }
    }
    private final static long TIME = 60 * 1000L;
    @RequestMapping("/check")
    public boolean getCaptcha(HttpSession session , String captcha){
        String key = (String) session.getAttribute(Session.getKey());
        Date date = (Date) session.getAttribute(Session.getDate());

        if (!StringUtils.hasLength(captcha)){
            return false;
        }
        if (key.equalsIgnoreCase(captcha) && System.currentTimeMillis() - date.getTime() < TIME){
            return true;
        }
        return false;
    }
}
